//
//  NSObject+Coder.m
//  归档解档
//
//  Created by 胡忠诚 on 15/7/5.
//  Copyright © 2015年 biyu6. All rights reserved.
//优化:归档解档子类属性时,也归档解档其继承自父类的属性

#import "NSObject+Coder.h"
#import <objc/runtime.h>
@implementation NSObject (Coder)

- (void)decode: (NSCoder *)decoder{
    Class cla = self.class;
    while (cla && cla != [NSObject class]) { //不归档NSObject的属性
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList(cla, &outCount);
        
        for (int i = 0; i < outCount; ++i) {
            Ivar ivar = ivars[i];
            NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
    //添加不解档的属性
            if ([self respondsToSelector:@selector(ignoredNames)]) {
                 if ([[self ignoredNames] containsObject:name]) continue;
            }

            id value = [decoder decodeObjectForKey:name];
            [self setValue:value forKey:name];
        }
            free(ivars);
        //获得父类
        cla = [cla superclass];
    }
}

- (void)encode: (NSCoder *)encoder{
    Class cla = self.class;
    while (cla && cla != [NSObject class]) { //不归档NSObject的属性
        
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList(cla, &outCount);

        for (int i = 0; i < outCount; ++i) {
            Ivar ivar = ivars[i];
            NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
            
    //添加不归档的属性
         if ([self respondsToSelector:@selector(ignoredNames)]) {
            if ([[self ignoredNames] containsObject:name]) continue;
        }
            
            id value = [self valueForKeyPath:name];
            [encoder encodeObject:value forKey:name];
        }
        free(ivars);
        //获得父类
        cla = [cla superclass];
    }
}
@end
